/*
 * 作者:熊猫
 * 日期:2017 - 3 - 20 9 - 41 - 46
 *
 */

package net.lainiao.morethread.Chapter7.demo11;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by Administrator on 2017/3/20.
 */
public class ParkingCounter extends AtomicInteger {
    private int maxNumber;
    public ParkingCounter(int maxNumber){
        set(0);
        this.maxNumber=maxNumber;
    }

    public boolean carIn(){
        for(;;){
            int value=get();
            if(value==maxNumber){
                System.out.println("ParkingCounter: The parking lot is full");
                return false;
            }else{
                int newValue=value+1;
                boolean changed=compareAndSet(value,newValue);
                if(changed){
                    System.out.println("ParkingCounter: A car has entered ");
                    return true;
                }
            }
        }
    }

    public boolean carOut(){
        for(;;){
            int value=get();
            if(value==0){
                System.out.println("ParkingCounter: The parking lot is Empty");
                return false;
            }else{
                int newValue=value-1;
                boolean changed=compareAndSet(value,newValue);
                if(changed){
                    System.out.println("ParkingCounter: A car has gone out ");
                    return true;
                }
            }
        }
    }

}
